package health_system.health_system.dto;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class MomentCommentTreeDTO {
    private Long momentId;
    private List<MomentCommentDTO> rootComments;
    private Integer totalCommentCount;
    
    /**
     * Creates a hierarchical comment tree from a flat list of comments
     */
    public static MomentCommentTreeDTO createTreeFromList(Long momentId, List<MomentCommentDTO> allComments) {
        // We will use this map to connect parents and children quickly
        Map<Long, MomentCommentDTO> commentMap = new HashMap<>();
        List<MomentCommentDTO> rootComments = new ArrayList<>();
        
        // First pass: add all comments to the map
        for (MomentCommentDTO comment : allComments) {
            // Create empty replies list if one doesn't exist
            if (comment.getReplies() == null) {
                comment.setReplies(new ArrayList<>());
            }
            commentMap.put(comment.getId(), comment);
        }
        
        // Second pass: connect parents and children
        for (MomentCommentDTO comment : allComments) {
            if (comment.getParentId() == null) {
                // This is a root comment
                rootComments.add(comment);
            } else {
                // This is a reply to another comment
                MomentCommentDTO parent = commentMap.get(comment.getParentId());
                if (parent != null && parent.getReplies() != null) {
                    parent.getReplies().add(comment);
                    // Update reply count
                    parent.setReplyCount(parent.getReplies().size());
                } else {
                    // If parent not found, treat as root comment
                    rootComments.add(comment);
                }
            }
        }
        
        // Create and return the tree DTO
        return MomentCommentTreeDTO.builder()
                .momentId(momentId)
                .rootComments(rootComments)
                .totalCommentCount(allComments.size())
                .build();
    }
} 